﻿/*
 * atomiclock.hpp
 *
 *  Created on: 2016年12月17日
 *      Author: work
 */

#ifndef INCLUDE_DM_OS_ATOMICLOCK_HPP_
#define INCLUDE_DM_OS_ATOMICLOCK_HPP_

#include <boost/atomic/atomic_flag.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

namespace dm{
namespace os{

class CAtomicLock{
public:
	typedef boost::atomic_flag lock_t;

	CAtomicLock( lock_t* ref ):m_ref(ref){
		if( ref->test_and_set() ){
			// 原来已经被锁定
			while( ref->test_and_set() );
		}
	}

	CAtomicLock( lock_t* ref,unsigned long msDelay ):m_ref(ref){
		if( ref->test_and_set() ){
			// 原来已经锁定
			 boost::posix_time::ptime s = boost::posix_time::microsec_clock().universal_time()+boost::posix_time::microseconds(msDelay);
			while( ref->test_and_set() )
				if( s<boost::posix_time::microsec_clock().universal_time() )
					break;
		}
	}

	~CAtomicLock(){
		m_ref->clear();
	}

private:
	lock_t* m_ref;
};
}
}



#endif /* INCLUDE_DM_OS_ATOMICLOCK_HPP_ */
